#include "lyrics.h"

#include <QFile>
#include <QDebug>
#include <QRegularExpression>

Lyrics::Lyrics(QString lyricsPath)
{
    this->lyrics_path = lyricsPath;
    max_size = 0;
}

Lyrics::~Lyrics()
{

}

QList<QString> Lyrics::getListLyricsText()
{
    return list_lyrics_text;
}

QVector<int> Lyrics::getListLyricsTime()
{
    return list_lyrics_time;
}

bool Lyrics::readLyricsFile(QString lyricsPath)
{
    if(lyrics_path == lyricsPath)
        return true;

    lyrics_path = lyricsPath;
    size = 0;
    QFile file(lyricsPath);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {

        QString line = "";

        while((line=file.readLine())>0)
        {
            //qDebug()<<line;
            analysisLyricsFile(line);
        }

        max_size = max_size < size ? size : max_size;
        return true;
    }
    else
    {
        return false;
    }

}

bool Lyrics::analysisLyricsFile(QString line)
{
    if(line == NULL || line.isEmpty())
    {
        qDebug()<<"This line is empty!";
        return false;
    }
    QRegularExpression regularExpression("\\[(\\d+)?:(\\d+\\.\\d+)?\\](.*)?");
    int index = 0;
    QRegularExpressionMatch match;
    match = regularExpression.match(line, index);

    if(match.hasMatch())
    {
        int totalTime;

        //qDebug()<<QString::fromStdString(match.captured(2).toStdString());
        totalTime = match.captured(1).toInt() * 60000 + match.captured(2).toFloat() * 1000;
        QString currentText =QString::fromStdString(match.captured(3).toStdString());

        if(size < list_lyrics_time.size())
        {
            list_lyrics_text[size] = currentText;
            list_lyrics_time[size++] = totalTime;
        }
        else
        {
            list_lyrics_text.push_back(currentText);
            list_lyrics_time.push_back(totalTime);
            size++;
        }

        return true;
    }

    return false;
}
